/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jsf;

import entidades.Rol;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import jpa.RolJpaController;
import jsf.util.JsfUtil;
import jpa.exceptions.NonexistentEntityException;

/**
 *
 * @author dvasquez
 */
public class RolController {

    public RolController() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        jpaController = (RolJpaController) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "rolJpa");
        converter = new RolConverter();
    }
    private Rol rol = null, rolSearch = new Rol();
    private List<Rol> rolItems = null;
    private RolJpaController jpaController = null;
    private RolConverter converter = null;
    private int ensayoItemsCount = 0;


    public SelectItem[] getRolItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(jpaController.findRolEntities(), false);
    }

    public SelectItem[] getRolItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(jpaController.findRolEntities(), true);
    }

    public Rol getRol() {
        if (rol == null) {
            rol = (Rol) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentRol", converter, null);
        }
        if (rol == null) {
            rol = new Rol();
        }
        return rol;
    }

    public int getEnsayoItemsCount() {
        ensayoItemsCount = rol.getEnsayoCollection().size();
        return ensayoItemsCount;
    }

    public void setEnsayoItemsCount(int rolItemsCount) {
        this.ensayoItemsCount = rolItemsCount;
    }

    public Rol getRolSearch(){
        if(rolSearch == null)
            rolSearch = new Rol();
        return rolSearch;
    }

    public String listSetup() {
        reset(true);
        return "rol_list";
    }

    public String createSetup() {
        reset(false);
        rol = new Rol();
        return "rol_create";
    }

    public String create() {
        try {
            jpaController.create(rol);
            JsfUtil.addSuccessMessage("El rol se ingresó exitosamente.");
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "Ocurrió un error de persistencia.");
            return null;
        }
        return listSetup();
    }

    public String detailSetup() {
        return scalarSetup("rol_detail");
    }

    public String editSetup() {
        return scalarSetup("rol_edit");
    }

    public String searchSetup(){
        rolSearch.setNombre("");
        return "rol_search";
    }

    private String scalarSetup(String destination) {
        reset(false);
        rol = (Rol) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentRol", converter, null);
        if (rol == null) {
            String requestRolString = JsfUtil.getRequestParameter("jsfcrud.currentRol");
            JsfUtil.addErrorMessage("El rol con nombre " + requestRolString + " ya no existe.");
            return relatedOrListOutcome();
        }
        return destination;
    }

    public String search(){
        actualizarRoles(true);
        return "rol_list";
    }

    public String edit() {
        String rolString = converter.getAsString(FacesContext.getCurrentInstance(), null, rol);
        String currentRolString = JsfUtil.getRequestParameter("jsfcrud.currentRol");
        if (rolString == null || rolString.length() == 0 || !rolString.equals(currentRolString)) {
            String outcome = editSetup();
            if ("rol_edit".equals(outcome)) {
                JsfUtil.addErrorMessage("No se pudo editar el rol. Por favor intente denuevo.");
            }
            return outcome;
        }
        try {
            jpaController.edit(rol);
            JsfUtil.addSuccessMessage("El rol se actualizó exitosamente.");
        } catch (NonexistentEntityException ne) {
            JsfUtil.addErrorMessage(ne.getLocalizedMessage());
            return listSetup();
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "Ocurrió un error de persistencia.");
            return null;
        }
        return detailSetup();
    }

    public String destroy() {
        String idAsString = JsfUtil.getRequestParameter("jsfcrud.currentRol");
        String id = idAsString;
        try {
            jpaController.destroy(id);
            JsfUtil.addSuccessMessage("El rol se eliminó exitosamente.");
        } catch (NonexistentEntityException ne) {
            JsfUtil.addErrorMessage(ne.getLocalizedMessage());
            return relatedOrListOutcome();
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "Ocurrió un error de persistencia.");
            return null;
        }
        return relatedOrListOutcome();
    }

    private String relatedOrListOutcome() {
        String relatedControllerOutcome = relatedControllerOutcome();
        if (relatedControllerOutcome != null) {
            return relatedControllerOutcome;
        }
        return listSetup();
    }

    public List<Rol> getRolItems() {
        if (rolItems == null) {
            //getPagingInfo();
            rolItems = jpaController.findRolEntities();
        }
        return rolItems;
    }


    private String relatedControllerOutcome() {
        String relatedControllerString = JsfUtil.getRequestParameter("jsfcrud.relatedController");
        String relatedControllerTypeString = JsfUtil.getRequestParameter("jsfcrud.relatedControllerType");
        if (relatedControllerString != null && relatedControllerTypeString != null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Object relatedController = context.getApplication().getELResolver().getValue(context.getELContext(), null, relatedControllerString);
            try {
                Class<?> relatedControllerType = Class.forName(relatedControllerTypeString);
                Method detailSetupMethod = relatedControllerType.getMethod("detailSetup");
                return (String) detailSetupMethod.invoke(relatedController);
            } catch (ClassNotFoundException e) {
                throw new FacesException(e);
            } catch (NoSuchMethodException e) {
                throw new FacesException(e);
            } catch (IllegalAccessException e) {
                throw new FacesException(e);
            } catch (InvocationTargetException e) {
                throw new FacesException(e);
            }
        }
        return null;
    }

    private void reset(boolean resetFirstItem) {
        rol = null;
        rolItems = null;
        //pagingInfo.setItemCount(-1);
        if (resetFirstItem) {
            //pagingInfo.setFirstItem(0);
        }
    }

    public void validateCreate(FacesContext facesContext, UIComponent component, Object value) {
        Rol newRol = new Rol();
        String newRolString = converter.getAsString(FacesContext.getCurrentInstance(), null, newRol);
        String rolString = converter.getAsString(FacesContext.getCurrentInstance(), null, rol);
        if (!newRolString.equals(rolString)) {
            createSetup();
        }
    }

    private void actualizarRoles(Boolean reset){
        String query = "select object(o) from Rol as o where o.nombre like :nombre";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters = createParameters(rolSearch);
        rolItems = jpaController.findRolEntities(jpaController.getRolCount(), 0, query, parameters);
        //reset(false,false);
        //getPagingInfo();
        //rolItems = rolTotal.subList(getPagingInfo().getFirstItem(), getPagingInfo().getLastItem());
    }

    private Map<String, Object> createParameters(Rol rol) {
        Map<String, Object> parameters = new HashMap<String, Object>();

        if (rol != null) {
            if (!rol.getNombre().equals("")) {
                parameters.put("nombre", "%" + rol.getNombre() + "%");
            } else {
                parameters.put("nombre", "%");
            }
            return parameters;
        }
        return null;
    }

    public Converter getConverter() {
        return converter;
    }

}
